﻿<script lang="ts" name="warehouseModel" setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import type { FormRules } from "element-plus";
import { useWarehouseModelApi } from '/@/api/interacting/warehouse/warehouseModel';
import { getDepartmentList, getUserList } from '/@/api/customer/userList';
import { useWarePlaceModelApi } from '/@/api/interacting/warehouse/warePlaceModel';
import { generateWarehouseCode } from '/@/utils/generateCode';
import { config } from "node:process";

//父级传递来的函数，用于回调
const emit = defineEmits(["reloadTable"]);
const warehouseModelApi = useWarehouseModelApi();
const warePlaceModelApi = useWarePlaceModelApi();
const ruleFormRef = ref();

const state = reactive({
	title: '',
	loading: false,
	showDialog: false,
	ruleForm: {} as any,
	stores: {},
	dropdownData: {} as any,
	departmentList: [] as any[], // 部门列表
	userList: [] as any[], // 用户列表
	warePlaceList: [] as any[], // 库位列表
});

// 自行添加其他规则
const rules = ref<FormRules>({
	wareCode: [{ required: true, message: '请选择仓库编码！', trigger: 'blur', },],
	wareName: [{ required: true, message: '请选择仓库名称！', trigger: 'blur', },],
	wareVolume: [{ required: true, message: '请选择仓库容量！', trigger: 'blur', },],
	wareType: [{ required: true, message: '请选择仓库状态！', trigger: 'blur', },],
	wareLock: [{ required: true, message: '请选择仓库锁定！', trigger: 'blur', },],
});

// 页面加载时
onMounted(async () => {
	// 加载部门列表
	try {
		const res = await getDepartmentList();
		// API直接返回数组，不需要访问result或data属性
		state.departmentList = Array.isArray(res) ? res : [];
		console.log('编辑对话框部门列表数据:', state.departmentList);
		console.log('编辑对话框部门列表长度:', state.departmentList.length);
	} catch (_error) {
		console.error('加载部门列表失败:', _error);
	}

	// 加载用户列表
	try {
		const res = await getUserList();
		console.log('编辑对话框用户列表API响应:', res);
		// 根据API响应结构，数据在result字段中
		let userList = res?.data?.result || res?.result || [];

		// 如果用户列表为空，尝试不同的数据结构
		if (userList.length === 0) {
			console.log('编辑对话框尝试其他数据结构...');
			userList = res?.data || res || [];
		}

		// 确保value是字符串格式，因为下拉框需要字符串值
		state.userList = userList.map((item: any) => ({
			...item,
			value: String(item.value), // 确保value是字符串
			label: item.label
		}));

		console.log('编辑对话框用户列表数据:', state.userList);
		console.log('编辑对话框用户列表长度:', state.userList.length);
	} catch (_error) {
		console.error('编辑对话框加载用户列表失败:', _error);
	}

	// 加载库位列表
	try {
		const res = await warePlaceModelApi.page({ page: 1, pageSize: 99999 });
		console.log('编辑对话框库位列表API响应:', res);
		// 根据API响应结构，数据在result字段中
		let warePlaceList = res?.data?.result?.items || [];
		// 转换为下拉框需要的格式
		state.warePlaceList = warePlaceList.map((item: any) => ({
			value: item.id,
			label: item.warePlaceName,
			code: item.warePlaceCode
		}));
	} catch (_error) {
		console.error('编辑对话框加载库位列表失败:', _error);
	}
});

// 生成仓库编码
const generateWareCode = async () => {
	try {
		// 查询现有的仓库编码
		const result = await warehouseModelApi.page({ page: 1, pageSize: 99999 });
		const existingCodes = result.data.result?.items?.map((item: any) => item.wareCode) || [];

		// 生成新的仓库编码
		const newCode = generateWarehouseCode(existingCodes);
		state.ruleForm.wareCode = newCode;

		ElMessage.success(`已生成仓库编码: ${newCode}`);
	} catch (error) {
		console.error('生成仓库编码失败:', error);
		ElMessage.error('生成仓库编码失败，请重试');
	}
};

// 打开弹窗
const openDialog = async (row: any, title: string) => {
	state.title = title;
	row = row ?? {};
	const formData = row.id ? await warehouseModelApi.detail(row.id).then(res => res.data.result) : JSON.parse(JSON.stringify(row));

	// 处理库位信息，将逗号分隔的字符串转换为数组（用于多选）
	if (formData.warePlaceId) {
		if (typeof formData.warePlaceId === 'string') {
			// 如果是字符串，按逗号分割成数组
			formData.warePlaceId = formData.warePlaceId.split(',').filter(id => id.trim());
		} else if (!Array.isArray(formData.warePlaceId)) {
			// 如果不是数组也不是字符串，转换为数组
			formData.warePlaceId = [String(formData.warePlaceId)];
		}
	} else {
		// 如果为空，设置为空数组
		formData.warePlaceId = [];
	}

	state.ruleForm = formData;
	state.showDialog = true;
};

// 关闭弹窗
const closeDialog = () => {
	emit("reloadTable");
	state.showDialog = false;
};

// 提交
const submit = async () => {
	ruleFormRef.value.validate(async (isValid: boolean, fields?: any) => {
		if (isValid) {
			try {
				state.loading = true;
				let values = { ...state.ruleForm };

				// 确保 userId 和 departmentId 是数字类型
				if (values.userId) {
					values.userId = parseInt(values.userId);
				}
				if (values.departmentId) {
					values.departmentId = parseInt(values.departmentId);
				}

				// 处理库位信息，将数组转换为逗号分隔的字符串（与后端数据库字段类型匹配）
				if (values.warePlaceId && Array.isArray(values.warePlaceId)) {
					values.warePlaceId = values.warePlaceId.join(',');
				} else if (values.warePlaceId && typeof values.warePlaceId !== 'string') {
					values.warePlaceId = String(values.warePlaceId);
				}

				console.log('提交的数据:', values);
				const result = await warehouseModelApi[state.ruleForm.id ? 'update' : 'add'](values);
				console.log('提交结果:', result.config.data);

				ElMessage.success(state.ruleForm.id ? '更新成功' : '新增成功');
				closeDialog();
			} catch (error) {
				console.error('提交失败:', error);
				ElMessage.error('操作失败，请检查数据是否正确');
			} finally {
				state.loading = false;
			}
		} else {
			ElMessage({
				message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
				type: "error",
			});
		}
	});
};

//将属性或者函数暴露给父组件
defineExpose({ openDialog });
</script>
<template>
	<div class="warehouseModel-container">
		<el-dialog v-model="state.showDialog" :width="800" draggable :close-on-click-modal="false">
			<template #header>
				<div style="color: #fff">
					<span>{{ state.title }}</span>
				</div>
			</template>
			<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="auto" :rules="rules">
				<el-row :gutter="35">
					<el-form-item v-show="false">
						<el-input v-model="state.ruleForm.id" />
					</el-form-item>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="仓库编码" prop="wareCode">
							<div style="display: flex; gap: 8px;">
								<el-input v-model="state.ruleForm.wareCode" placeholder="请输入仓库编码" maxlength="64"
									show-word-limit clearable />
								<el-button type="primary" @click="generateWareCode" :icon="'ele-Refresh'">生成</el-button>
							</div>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="仓库名称" prop="wareName">
							<el-input v-model="state.ruleForm.wareName" placeholder="请输入仓库名称" maxlength="128"
								show-word-limit clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="仓库容量" prop="wareVolume">
							<el-input-number v-model="state.ruleForm.wareVolume" placeholder="请输入仓库容量" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="库管部门" prop="departmentId">
							<el-select v-model="state.ruleForm.departmentId" clearable filterable placeholder="请选择库管部门">
								<el-option v-for="item in state.departmentList" :key="item.value" :label="item.label"
									:value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="仓库主管" prop="userId">
							<el-select v-model="state.ruleForm.userId" clearable filterable placeholder="请选择仓库主管">
								<el-option v-for="item in state.userList" :key="item.value" :label="item.label"
									:value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="仓库地址" prop="wareAddr">
							<el-input v-model="state.ruleForm.wareAddr" placeholder="请输入仓库地址" maxlength="256"
								show-word-limit clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="仓库状态" prop="wareType">
							<el-switch v-model="state.ruleForm.wareType" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="仓库锁定" prop="wareLock">
							<el-switch v-model="state.ruleForm.wareLock" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="仓库备注" prop="wareNote">
							<el-input v-model="state.ruleForm.wareNote" placeholder="请输入仓库备注" maxlength="512"
								show-word-limit clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="库位信息" prop="warePlaceId">
							<el-select v-model="state.ruleForm.warePlaceId" multiple clearable filterable placeholder="请选择库位信息" collapse-tags collapse-tags-tooltip>
								<el-option v-for="item in state.warePlaceList" :key="item.value" :label="`${item.label}`"
									:value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="软删除时间" prop="deleteTime">
							<el-date-picker v-model="state.ruleForm.deleteTime" type="date" placeholder="软删除时间" />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="() => state.showDialog = false" :disabled="state.loading">取 消</el-button>
					<el-button @click="submit" type="primary" :loading="state.loading" v-reclick="1000">确 定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<style lang="scss" scoped>
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}
</style>